package com.rgs.springboot.conditional;


import com.rgs.springboot.annotate.RgsConditionalOnClass;
import org.springframework.context.annotation.Condition;
import org.springframework.context.annotation.ConditionContext;
import org.springframework.core.type.AnnotatedTypeMetadata;

import java.util.Map;

/**
 * @author RenGaoshuai
 * @date 2024/7/2 11:03
 * @description 自定义条件注释
 */
public class RgsOnClassCondition implements Condition {
    @Override
    public boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata) {

        //元数据获取这个注解上信息
        Map<String, Object> annotationAttributes = metadata.getAnnotationAttributes(RgsConditionalOnClass.class.getName());

        String className = (String) annotationAttributes.get("className");

        try {
            //去加载这个注解上className这个类，如果这个类加载成功了，那么说明项目组有这个类的依赖
            context.getClassLoader().loadClass(className);
            return true;
        }catch (Exception e){
            return false;
        }
    }
}
